<script setup lang="ts">
import { ref } from 'vue'
import type { PostLoginPayload } from '@/api/user/user'
import type { FormRules } from 'element-plus'
import useUserStore from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()

const user = useUserStore()

// do not use same name with ref
const form = ref<PostLoginPayload>({
  username: '神龙教主',
  password: 'admin888',
})

const loginRules = ref<FormRules<PostLoginPayload>>({
  username: [{ required: true, message: '请输入', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入', trigger: 'blur' },
    {
      min: 6,
      max: 12,
      message: '请输入6-12位',
    },
  ],
})

const logonFormRef = ref()

// 登录方法
const onSubmit = () => {
  // 兜底校验
  logonFormRef.value.validate(async (vaild: any) => {
    if (!vaild) return
    await user.login(form.value)
    router.push('/')
  })
}
</script>

<template>
  <div class="login">
    <div class="container">
      <div class="img">
        <img src="/src/assets/image/login1Bg-74a8e9c4.png" alt="" />
      </div>

      <div class="formBox">
        <el-form
          :model="form"
          :rules="loginRules"
          label-width="auto"
          style="max-width: 600px"
          ref="logonFormRef"
        >
          <el-form-item prop="username">
            <el-input v-model="form.username" type="text" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="form.password" type="password" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login {
  height: 100%;
  width: 100%;
  padding: 25px;
  border-radius: 8px;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  align-items: center;

  .container {
    background-color: #fff;
    width: 100%;
    height: 100%;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    .img {
      width: 50%;
      height: 100%;
      img {
        width: 100%;
        object-fit: cover;
      }
    }
    .formBox {
      width: 50%;
      padding: 30px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
